package com.sq.partner.manager.controller;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sq.partner.manager.common.Config;
import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.DictCache;
import com.sq.partner.manager.common.exception.AppException;
import com.sq.partner.manager.mybatis.model.DictDto;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.NocarConInsu;
import com.sq.partner.manager.mybatis.model.NocarProd;
import com.sq.partner.manager.mybatis.model.NocarProdDefalut;
import com.sq.partner.manager.mybatis.model.NocarRisk;
import com.sq.partner.manager.mybatis.model.NocarRiskCal;
import com.sq.partner.manager.mybatis.model.TradProdProp;
import com.sq.partner.manager.service.IGatewayNoCarProductService;
import com.sq.partner.manager.service.INlifeProdConfigService;
import com.sq.partner.manager.util.FreeMarkerUtil;
import com.sq.partner.manager.util.JsonUtils;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.Page;
import com.sq.partner.manager.util.StrUtil;

import java.util.List;
import java.util.Map;
/**
 * 
 * @author guozizhou
 * @date 2015-04-18
 * 财险产品配置定义
 */
@Controller
@RequestMapping("/noCarProduct")
public class NoCarProductController {
	private static Logger logger = LogUtil.getLog(NoCarProductController.class);

	private static BigDecimal percentHun = new BigDecimal(100);// 百分比
	private static BigDecimal percentTh = new BigDecimal(1000);// 千分比
	private static BigDecimal conPropPercent = BigDecimal.valueOf(1.000000);// 共保协议必须等于1
	@Resource
	private INlifeProdConfigService nProductService;
	@Resource
	IGatewayNoCarProductService noCarProductService;

	/**
	 * 跳转产品列表页面
	 */
	@RequestMapping(value = "/list")
	public String productDefinition(ModelMap model, HttpServletRequest request) throws Exception {
		List<DictDto> agentTypeList = DictCache.getDict(Constants.DICT_AGENT_TYPE);
		//清单内容
		List<DictDto> tgtTypeList = DictCache.getDict("tgt_type");
		model.put("tgtTypeList", tgtTypeList);
		model.put("agentTypeList", agentTypeList);
		return "noCarProduct/list";
	}

	/**
	 * 跳转添加产品页面
	 */
	@RequestMapping(value = "/add")
	public String add(ModelMap model, HttpServletRequest request) throws Exception {
		List<DictDto> agentTypeList = DictCache.getDict(Constants.DICT_AGENT_TYPE);
		//清单内容
		List<DictDto> tgtTypeList = DictCache.getDict("tgt_type");
		model.put("tgtTypeList", tgtTypeList);
		model.put("agentTypeList", agentTypeList);
		return "noCarProduct/add";
	}

	/**
	 * 点击配置险别按钮触发该方法:
	 * 根据产品类型进行控制分发跳转添加险别页面
	 */
	@RequestMapping(value = "/prodRisk")
	public String prodPlan(ModelMap model, HttpServletRequest request, String prodType, String prodCode) throws Exception {
		logger.info("产品类型" + prodType + "产品编码" + prodCode);
		NocarProd prod = noCarProductService.queryNocarTradProdInstById(prodCode);
		if (null == prod) {
			throw new Exception("产品代码不存在");
		}
		List<DictDto> riskTypeList = DictCache.getDict(Constants.DICT_RISK_CAL_TYPE);
		List<DictDto> insureItemList = DictCache.getDict(Constants.DICT_INSURE_ITEM_012A);
		List<DictDto> insureItemList012b = DictCache.getDict(Constants.DICT_INSURE_ITEM_012B);
		List<DictDto> insureItem09CList = DictCache.getDict(Constants.DICT_INSURE_ITEM_090C);
		List<DictDto> insureValTypeList = DictCache.getDict(Constants.DICT_INSURE_VAL_AFF_TYP);
		List<DictDto> insureValTypeList012B = DictCache.getDict(Constants.DICT_INSURE_VAL_AFF_012B);
		List<DictDto> prodTypeList = DictCache.getProdType(prod.getProdType());
		List<DictDto> insureItem081FList = DictCache.getDict(Constants.DICT_INSURE_ITEM_081F);
		List<DictDto>  masterTypes = DictCache.getDict(Constants.DICT_MASTER_080B);
		model.put("insureItemList", insureItemList);
		model.put("insureItemList012b", insureItemList012b);
		model.put("insureItem09CList", insureItem09CList);
		model.put("insureValTypeList", insureValTypeList);
		model.put("insureValTypeList012B", insureValTypeList012B);
		model.put("masterTypes", masterTypes);
		model.put("insureItem081FList", insureItem081FList);
		model.put("riskCode", prodTypeList);
		model.put("riskCalTypeList", riskTypeList);
		model.put("prodCode", prodCode);
		model.put("prodType", prod.getProdType());
		model.put("prodName", prod.getProdName());
		return "noCarProduct/risk/risk_" + prodType + "_add";
	}

	/**
	 * 查询产品列表
	 */
	@RequestMapping(value = "/queryList")
	public @ResponseBody Page<NocarProd> queryList(HttpServletRequest request,Integer size, Integer current, String prodCode, String prodName, String status, String startDate,
			String endDate) throws SQLException {
		Page<NocarProd> page = new Page<NocarProd>();
		page.setCurrent(current);
		page.setSize(size);
		NocarProd noCarProd = new NocarProd();
		noCarProd.setProdCode(prodCode);
		noCarProd.setProdName(prodName);
		noCarProd.setStatus(status);
		noCarProd.setVstartDate(startDate);
		noCarProd.setVendDate(endDate);
		page.setType(noCarProd);
		/*是否具有导出产品权限用户*/
		boolean flag=false;
		HttpSession  session=request.getSession();
		GatewayUser  user=(GatewayUser) session.getAttribute(Constants.SESSION_USER);
		String usersConfig=Config.getProp("imple.nlife.userCodes");
		String[] codes=separete(usersConfig);
		if(codes!=null&&codes.length>0){
			flag=Arrays.asList(codes).contains(user.getUserCode());
		}
		page.setObj(flag);
		return noCarProductService.queryPage(page);
	}

	private String[] separete(String usersConfig) {
		if(StrUtil.isEmpty(usersConfig)){
			return null;
		}
		String[] strs=usersConfig.split(",");
		return strs;
	}

	/**
	 * 保存产品信息
	 * ,Long longestCancelDay 最长起保后注销天数（去除）
	 */
	@RequestMapping(value = "/save")
	public @ResponseBody Page<NocarProd> saveTradProdInst(String prodName, String prodType, String status, String isPool, String prodDesc, Long maxDelayDay,
			Long minDays, Long maxDays, String agentType, String conInsuCode, String pppUnit ,Long minDelayDay,String minDelayUnit,String tgtType ) throws Exception {
		Page<NocarProd> page = new Page<NocarProd>();

		if (StrUtil.isEmpty(prodName)) {
			page.setMessage("产品名称不能为空");
			page.setResult("error");
			return page;
		}

		if (StrUtil.isEmpty(prodType)) {
			page.setMessage("产品型归类不能为空");
			page.setResult("error");
			return page;
		}
		if ("Y".equals(isPool) && StrUtil.isEmpty(conInsuCode)) {
			page.setMessage("共保方式不能为空");
			page.setResult("error");
			return page;
		}
		if (StrUtil.isEmpty(maxDelayDay)) {
			/*
			 * page.setMessage("最长延时起保天数不能为空"); page.setResult("error"); return
			 * page;
			 */
		} else {
			Pattern pattern = Pattern.compile("(0|[1-9][0-9]*)");
			Matcher matcher = pattern.matcher(maxDelayDay.toString());
			if (!matcher.matches()) {
				page.setMessage("最长延时起保天数必须是不小于0的整数");
				page.setResult("error");
				return page;
			}
		}
		if(StrUtil.isEmpty(minDelayDay)){
			page.setMessage("最短延时起保天数不能为空");
			page.setResult("error");
			return page;
		}else{
			Pattern pattern = Pattern.compile("^(0|[1-9][0-9]*|-[1-9][0-9]*)$");  
	        Matcher matcher = pattern.matcher(minDelayDay.toString());
	        if(!matcher.matches()){
				page.setMessage("最短延时起保天数必须是不小于0的整数");
				page.setResult("error");
				return page;
	        }
		}
		/*if(StrUtil.isEmpty(longestCancelDay)){
			page.setMessage("最长注销天数不能为空");
			page.setResult("error");
			return page;
		}else{
			Pattern pattern = Pattern.compile("^(0|[1-9][0-9]*)$");  
	        Matcher matcher = pattern.matcher(longestCancelDay.toString());
	        if(!matcher.matches()){
				page.setMessage("最长注销天数必须是不小于0的整数");
				page.setResult("error");
				return page;
	        }
		}*/
		
		
		if (StrUtil.isEmpty(minDays)) {
			/*
			 * page.setMessage("最短保险天数不能为空"); page.setResult("error"); return
			 * page;
			 */
		} else {
			Pattern pattern = Pattern.compile("[1-9][0-9]*");
			Matcher matcher = pattern.matcher(minDays.toString());
			if (!matcher.matches()) {
				page.setMessage("最小保险期间必须是不小于1的整数");
				page.setResult("error");
				return page;
			}
		}

		if (StrUtil.isEmpty(maxDays)) {
			/*
			 * page.setMessage("最长保险天数不能为空"); page.setResult("error"); return
			 * page;
			 */
		} else {
			Pattern pattern = Pattern.compile("[1-9][0-9]*");
			Matcher matcher = pattern.matcher(maxDays.toString());
			if (!matcher.matches()) {
				page.setMessage("最大保险期间必须是不小于1的整数");
				page.setResult("error");
				return page;
			} else {
				if (StrUtil.isEmpty(minDays)) {
					page.setMessage("当录入最大保险期间时最小保险期间不能为空");
					page.setResult("error");
					return page;
				}
				if (maxDays < minDays) {
					page.setMessage("最大保险期间不能小于最小保险期间");
					page.setResult("error");
					return page;
				}
			}
		}
		/*if (StrUtil.isEmpty(agentType)) {
			page.setMessage("请选择销售类型");
			page.setResult("error");
			return page;
		}*/
		NocarProd nocarProd = new NocarProd();
		nocarProd.setProdName(prodName);
		nocarProd.setProdType(prodType);
		nocarProd.setIsPool(isPool);
		nocarProd.setStatus("0");
		nocarProd.setProdDesc(prodDesc);
		nocarProd.setMaxDelayDay(maxDelayDay);
		nocarProd.setMaxDays(maxDays);
		nocarProd.setMinDays(minDays);
		nocarProd.setPppUnit(pppUnit);
	/*	nocarProd.setAgentType(agentType);*/
		nocarProd.setConInsuCode(conInsuCode);
		nocarProd.setMinDelayDay(minDelayDay);
		/*nocarProd.setLongestCancelDay(longestCancelDay);*/
		nocarProd.setMinDelayUnit(minDelayUnit);
		nocarProd.setTgtType(tgtType);
		// 目的得到添加产品编号便与险种配置
		page.setType(noCarProductService.saveNoCarTradProdInst(nocarProd));
		return page;
	}

	/**
	 * 更新产品信息
	 * ,Long longestCancelDay 最长起保后注销天数（去除）
	 */
	@RequestMapping(value = "/updateNocarProd")
	public @ResponseBody Page<NocarProd> updateNocarProd(String prodCode, String prodName, String prodType, String status, String isPool, String prodDesc,
			Long maxDelayDay, Long minDays, Long maxDays, String agentType, String conInsuCode, String originalIsPools, String pppUnit,Long minDelayDay ,
			String minDelayUnit,String tgtType
			) throws Exception {
		Page<NocarProd> page = new Page<NocarProd>();

		if (StrUtil.isEmpty(prodName)) {
			page.setMessage("产品名称不能为空");
			page.setResult("error");
			return page;
		}

		if (StrUtil.isEmpty(prodType)) {
			page.setMessage("产品型归类不能为空");
			page.setResult("error");
			return page;
		}
		if ("1".equalsIgnoreCase(status)) {
			// 若支持共保且没有配置共保信息，则不允许更新为有效状态
			if ("Y".equals(isPool) && !(noCarProductService.searchProdConInsureInfoByProdCode(prodCode))) {
				page.setResult("error");
				page.setMessage("共保信息配置未完成产品只能为无效状态！请先配置共保信息后修改状态");
				return page;
			}
			if (0 == noCarProductService.queryProdRiskCountByCode(prodCode)) {
				page.setResult("other");
				return page;
			}
		} else {
			if (isExistProdPlan(prodCode)) {
				page.setMessage("您选择的产品已配置投保方案信息，不允许改为无效");
				page.setResult("error");
				return page;
			}
		}
		if (StrUtil.isEmpty(maxDelayDay)) {
			/*
			 * page.setMessage("最长延时起保天数不能为空"); page.setResult("error"); return
			 * page;
			 */
		} else {
			Pattern pattern = Pattern.compile("(0|[1-9][0-9]*)");
			Matcher matcher = pattern.matcher(maxDelayDay.toString());
			if (!matcher.matches()) {
				page.setMessage("最长延时起保天数必须是不小于0的整数");
				page.setResult("error");
				return page;
			}
		}
		if(StrUtil.isEmpty(minDelayDay)){
			page.setMessage("最短延时起保天数不能为空");
			page.setResult("error");
			return page;
		}else{
			Pattern pattern = Pattern.compile("^(0|[1-9][0-9]*|-[1-9][0-9]*)$");  
	        Matcher matcher = pattern.matcher(minDelayDay.toString());
	        if(!matcher.matches()){
				page.setMessage("最短延时起保天数必须是不小于0的整数");
				page.setResult("error");
				return page;
	        }
		}
		/*if(StrUtil.isEmpty(longestCancelDay)){
			page.setMessage("最长注销天数不能为空");
			page.setResult("error");
			return page;
		}else{
			Pattern pattern = Pattern.compile("^(0|[1-9][0-9]*)$");  
	        Matcher matcher = pattern.matcher(longestCancelDay.toString());
	        if(!matcher.matches()){
				page.setMessage("最长注销天数必须是不小于0的整数");
				page.setResult("error");
				return page;
	        }
		}*/
		if (StrUtil.isEmpty(minDays)) {
			/*
			 * page.setMessage("最短保险天数不能为空"); page.setResult("error"); return
			 * page;
			 */
		} else {
			Pattern pattern = Pattern.compile("[1-9][0-9]*");
			Matcher matcher = pattern.matcher(minDays.toString());
			if (!matcher.matches()) {
				page.setMessage("最小保险期间必须是不小于1的整数");
				page.setResult("error");
				return page;
			}
		}
		if (StrUtil.isEmpty(maxDays)) {
			/*
			 * page.setMessage("最长保险天数不能为空"); page.setResult("error"); return
			 * page;
			 */
		} else {
			Pattern pattern = Pattern.compile("[1-9][0-9]*");
			Matcher matcher = pattern.matcher(maxDays.toString());
			if (!matcher.matches()) {
				page.setMessage("最大保险期间必须是不小于1的整数");
				page.setResult("error");
				return page;
			} else {
				if (StrUtil.isEmpty(minDays)) {
					page.setMessage("当录入最大保险期间时最小保险期间不能为空");
					page.setResult("error");
					return page;
				}
				if (maxDays < minDays) {
					page.setMessage("最大保险期间不能小于最小保险期间");
					page.setResult("error");
					return page;
				}
			}
		}

		if (StrUtil.isEmpty(minDays)) {
			/*
			 * page.setMessage("最短保险天数不能为空"); page.setResult("error"); return
			 * page;
			 */
		} else {
			Pattern pattern = Pattern.compile("[1-9][0-9]*");
			Matcher matcher = pattern.matcher(minDays.toString());
			if (!matcher.matches()) {
				page.setMessage("最短保险天数必须是不小于1的整数");
				page.setResult("error");
				return page;
			}
		}
		/**
		 * 销售类型
		 */
		/*if (StrUtil.isEmpty(agentType)) {
			page.setMessage("请选择销售类型");
			page.setResult("error");
			return page;
		}*/
		if ("N".equals(isPool)) {
			// 1.del consInsuInfo
			noCarProductService.deleteProdConInsureByProdCode(prodCode);
		} else if ("Y".equals(isPool)) {
			if (StrUtil.isEmpty(conInsuCode)) {
				page.setMessage("共保方式不能为空，请选择");
				page.setResult("error");
				return page;
			}
		}
		if ("1".equals(status) && "N".equals(originalIsPools) && "Y".equals(isPool)) {
			page.setMessage("是否共保由[否]改为[是]由于未配置共保信息，产品状态只能修改为无效");
			page.setResult("error");
			return page;
		}
		NocarProd nocarProd = new NocarProd();
		nocarProd.setProdCode(prodCode);
		nocarProd.setProdName(prodName);
		nocarProd.setProdType(prodType);
		nocarProd.setIsPool(isPool);
		nocarProd.setStatus(status);
		nocarProd.setProdDesc(prodDesc);
		nocarProd.setInsertTime(new Date());
		nocarProd.setMaxDelayDay(maxDelayDay);
		nocarProd.setMaxDays(maxDays);
		nocarProd.setMinDays(minDays);
		nocarProd.setPppUnit(pppUnit);
/*		nocarProd.setAgentType(agentType);*/
		nocarProd.setConInsuCode(conInsuCode);
		nocarProd.setMinDelayDay(minDelayDay);
		/*nocarProd.setLongestCancelDay(longestCancelDay);*/
		nocarProd.setMinDelayUnit(minDelayUnit);
		nocarProd.setTgtType(tgtType);
		// 目的得到添加产品编号便与险种配置
		noCarProductService.updateNocarProd(nocarProd);
		page.setMessage("更新成功");
		return page;
	}

	/**
	 * 删除产品
	 */
	@RequestMapping(value = "/delNocarProd")
	public @ResponseBody Page<NocarRisk> deleteNocarProd(String prodCode) throws Exception {
		Page<NocarRisk> page = new Page<NocarRisk>();
		if (StrUtil.isEmpty(prodCode)) {
			page.setMessage("产品代码不能为空");
			page.setResult("error");
			return page;
		}

		NocarProd oldNocarProd = this.noCarProductService.queryNocarTradProdInstById(prodCode);
		if (null != oldNocarProd && StrUtil.isNotEmpty(oldNocarProd.getStatus())) {
			if ("0".equals(oldNocarProd.getStatus())) {
				if (isExistProdPlan(prodCode)) {
					page.setMessage("您选择的产品已配置投保方案信息，不允许删除");
					page.setResult("error");
					return page;
				}
			} else {
				page.setMessage("您选择的产品当前为有效状态,暂不能删除");
				page.setResult("error");
				return page;
			}
		}

		noCarProductService.deleteRiskByProdCode(prodCode);
		noCarProductService.deleteProdConInsureByProdCode(prodCode);// 删除共保信息配置
		noCarProductService.deleteNocarProd(prodCode);
		page.setMessage("删除成功");
		return page;
	}

	/**
	 * 插入险别信息
	 */
	@RequestMapping(value = "/saveRisk")
	public @ResponseBody Page<NocarRisk> saveRisk(NocarRisk noCarRisk,String prodType) throws Exception {
		Page<NocarRisk> page = fieldVerification(noCarRisk,prodType);
		if("error".equals(page.getResult())){
			return page;
		}
		/**080B相同险种下标的是否相同*/
		if("080B".equals(prodType)){
			Map<String, Object> map=new HashMap<String, Object>();
			map.put("prodCode", noCarRisk.getProdCode());
			map.put("riskCode", noCarRisk.getRiskCode());
			map.put("cField9", noCarRisk.getcField9());
			if(checkMast(map)){
				page.setMessage("已经存在相同险种,标的");
				page.setResult("error");
				return page;
			}
		}
		NocarRisk temNocarRisk = new NocarRisk();
		temNocarRisk.setRiskCode(noCarRisk.getRiskCode());
		temNocarRisk.setProdCode(noCarRisk.getProdCode());
		// 查询险别当前的最大序号
		temNocarRisk = noCarProductService.findMaxRiskProdIndex(temNocarRisk);
		if (null != temNocarRisk && null != temNocarRisk.getnField1()) {
			noCarRisk.setnField1(temNocarRisk.getnField1() + 1);
		} else {
			noCarRisk.setnField1(1l);
		}
		// 执行insert操作
		logger.info("保存险种信息:" + noCarRisk.getRiskName());
		noCarProductService.saveRisk(noCarRisk);
		page.setMessage("保存成功");
		return page;
	}
	
	/**080B标的信息处理**/
	private boolean checkMast(Map<String, Object> map){
		boolean flag=false;
		try {
			flag=noCarProductService.findNocarByMap(map);
		} catch (SQLException e) {
			logger.info("查询标的报错"+e);
		}
		return flag;
	}
	/**
	 * 更新险别信息
	 */
	@RequestMapping(value = "/riskUpdate")
	public @ResponseBody Page<NocarRisk> updateRisk(NocarRisk noCarRisk,String prodType) throws Exception {
		Page<NocarRisk> page = fieldVerification(noCarRisk,prodType);
		if("error".equals(page.getResult())){
			return page;
		}
		/**080B相同险种下标的是否相同*/
		if("080B".equals(prodType)){
			Map<String, Object> map=new HashMap<String, Object>();
			map.put("prodCode", noCarRisk.getProdCode());
			map.put("riskCode", noCarRisk.getRiskCode());
			map.put("cField9", noCarRisk.getcField9());
			/**相同险种必须不同标的*/
			if(checkMast(map)){
				map.put("nField1", noCarRisk.getnField1());
				/**判断是否有重复*/
				if(!checkMast(map)){
					page.setMessage("已经存在相同险种,标的");
					page.setResult("error");
					return page;
				}
			}
		}
		// 执行更新操作
		logger.info("更新险种信息:" + noCarRisk.getRiskName());
		noCarProductService.updateRisk(noCarRisk);
		page.setMessage("更新成功");
		return page;
	}	
	/**
	 * 险种字段校验
	 * @param noCarRisk
	 * @param prodType
	 * @return
	 */
	private Page<NocarRisk> fieldVerification(NocarRisk noCarRisk,String prodType){
		Page<NocarRisk> page = new Page<NocarRisk>();
		if (StrUtil.isEmpty(prodType)) {
			page.setMessage("产品类型不能为空");
			page.setResult("error");
			return page;
		}
		if (StrUtil.isEmpty(noCarRisk.getProdCode())) {
			page.setMessage("产品代码不能为空");
			page.setResult("error");
			return page;
		}
		if (StrUtil.isEmpty(noCarRisk.getRiskCode())) {
			page.setMessage("险别代码不能为空");
			page.setResult("error");
			return page;
		}
		/*
		 * if(isExistRisk(prodCode,riskCode)) {
		 * page.setMessage("该产品本险别已经添加，请勿同一产品重复添加同一险别");
		 * page.setResult("error"); return page; }
		 */
			if (StrUtil.isEmpty(noCarRisk.getRiskCalType())) {
				page.setMessage("保费计算方式不能为空");
				page.setResult("error");
				return page;
			}
		
		//amount假如不为空,长度校验及转换
		BigDecimal fAmount = noCarRisk.getAmount();
		if(fAmount!=null){
			String amountStr = fAmount.toString();
			if (amountStr.indexOf(".")>0) {
				amountStr = amountStr.substring(0, amountStr.indexOf("."));
			}
			if (amountStr.length() > 8) {
				page.setMessage("输入 "+getAmountName(prodType)+"长度不能超过8位数字");
				page.setResult("error");
				return page;
			}
			try {
				DecimalFormat df = new DecimalFormat("#.00");
				fAmount = new BigDecimal(df.format(fAmount));
				noCarRisk.setAmount(fAmount);
			} catch (Exception e) {
				page.setMessage("输入 "+getAmountName(prodType)+"不合法");
				page.setResult("error");
				logger.info("输入 "+getAmountName(prodType)+"不合法", e);
				return page;
			}
		}
		
		/*
		 * 产品字段检验分类
		 * 1.amount非空校验： 021M 080D 080E 048C 049B
		 * 2.特殊单独校验：042O 081R 081X 081K 081F 080G 04A5
		 * 3.不做校验：090C 043T 048K 012A 012B 081J
		 */
		
		if("021M".equals(prodType)||"080D".equals(prodType)||"080E".equals(prodType)||"048C".equals(prodType)||"049B".equals(prodType)){
			if (fAmount==null) {
				page.setMessage( getAmountName(prodType)+"不能为空");
				page.setResult("error");
				return page;
			}
		}else if ("042O".equals(prodType)) {
			/***********累计责任限额校验*********/
			if (fAmount==null) {
				page.setMessage(getAmountName(prodType)+"不能为空");
				page.setResult("error");
				return page;
			} 
			/***********每次事故责任限额校验*********/
			Pattern pnum = Pattern.compile("^(([1-9]\\d{0,9})|0)(\\.\\d{1,2})?$");
			DecimalFormat df = new DecimalFormat("#.00");
			if (null == noCarRisk.getnField8()) {
				page.setMessage("每次事故责任限额不能为空");
				page.setResult("error");
				return page;
			} else {
				if (!pnum.matcher(df.format(noCarRisk.getnField8())).matches()) {
					page.setMessage("输入每次事故责任限额不合法");
					page.setResult("error");
					return page;
				}
				try {
					noCarRisk.setnField8(new BigDecimal(df.format(noCarRisk.getnField8())));
				} catch (Exception e) {
					page.setMessage("输入的每次事故责任限额不合法");
					page.setResult("error");
					logger.info("输入的每次事故责任限额不合法", e);
					return page;
				}
			}

			if (null == noCarRisk.getnField17()) {
				page.setMessage("基准费率不能为空");
				page.setResult("error");
				return page;
			} else {
				if (!pnum.matcher(noCarRisk.getnField17().toString()).matches()) {
					page.setMessage("输入基准费率不合法");
					page.setResult("error");
					return page;
				}
			}
			Pattern pnum1 = Pattern.compile("^(([1-9]\\d{0,9})|0)(\\.\\d{1,20})?$");

			if (null == noCarRisk.getnField18()) {
				page.setMessage("实际费率不能为空");
				page.setResult("error");
				return page;
			} else {
				if (!pnum1.matcher(noCarRisk.getnField18().toString()).matches()) {
					page.setMessage("输入实际费率不合法");
					page.setResult("error");
					return page;
				}
			}
			if (null == noCarRisk.getnField15()) {
				page.setMessage("调整系数不能为空");
				page.setResult("error");
				return page;
			} else {
				if (!pnum.matcher(noCarRisk.getnField15().toString()).matches()) {
					page.setMessage("输入调整系数不合法");
					page.setResult("error");
					return page;
				}
			}
		}else if ("081R".equals(prodType)) {
			if (fAmount==null){
				page.setMessage(getAmountName(prodType)+"不能为空");
				page.setResult("error");
				return page;
			}
			if (null == noCarRisk.getnField7()){
				page.setMessage("基准保费不能为空");
				page.setResult("error");
				return page;
			} 
			if (null == noCarRisk.getnField6()){
				page.setMessage("起赔点不能为空");
				page.setResult("error");
				return page;
			} 
		}else if("080G".equals(prodType)){
			Pattern pnum = Pattern.compile("^(([1-9]\\d{0,9})|0)(\\.\\d{1,2})?$");
			DecimalFormat df = new DecimalFormat("#.00");
			//每次事故赔偿限额（元）校验
			if(null == noCarRisk.getnField6()){
				page.setMessage("每次事故赔偿限额（元）不能为空");
				page.setResult("error");
				return page;
			}else{ 
				
				if(!pnum.matcher(noCarRisk.getnField6().toString()).matches()){  
				page.setMessage("每次事故赔偿限额（元）不合法");
				page.setResult("error");
				return page;
				}
				try {
					noCarRisk.setnField6(new BigDecimal(df.format(noCarRisk.getnField6())));
				} catch (Exception e) {
					page.setMessage("输入的每次事故责任限额不合法");
					page.setResult("error");
					logger.info("输入的每次事故责任限额不合法", e);
					return page;
				}
		    }
			//基准税率校验
			if (null == noCarRisk.getnField17()) {
				page.setMessage("基准费率不能为空");
				page.setResult("error");
				return page;
			} else {
				if (!pnum.matcher(noCarRisk.getnField17().toString()).matches()) {
					page.setMessage("输入基准费率不合法");
					page.setResult("error");
					return page;
				}
			}
		}else if("081X".equals(prodType)){
			if (fAmount==null) {
				page.setMessage(getAmountName(prodType)+"不能为空");
				page.setResult("error");
				return page;
			}
			if (null == noCarRisk.getnField18()) {
				page.setMessage("实际费率不能为空");
				page.setResult("error");
				return page;
			}
		}else if("081K".equals(prodType)){
			if (fAmount==null) {
				page.setMessage(getAmountName(prodType)+"不能为空");
				page.setResult("error");
				return page;
			}
			if (null == noCarRisk.getnField15()) {
				page.setMessage("调整系数不能为空");
				page.setResult("error");
				return page;
			}
			if (null == noCarRisk.getnField17()) {
				page.setMessage("基准费率（‰）不能为空");
				page.setResult("error");
				return page;
			}
			if (null == noCarRisk.getnField18()) {
				page.setMessage("实际费率（‰）不能为空");
				page.setResult("error");
				return page;
			}
		}else if("081F".equals(prodType)){
			if (null == noCarRisk.getcField1()) {
				page.setMessage("机票类型不能为空");
				page.setResult("error");
				return page;
			}
			if (null == noCarRisk.getnField7()) {
				page.setMessage("实际保费（元）不能为空");
				page.setResult("error");
				return page;
			}
		}else if("04A5".equals(prodType)){
			Pattern pnum = Pattern.compile("^(([1-9]\\d{0,9})|0)(\\.\\d{1,2})?$");
			DecimalFormat df = new DecimalFormat("#.00");
			//每次事故每人人身伤亡赔偿（元）校验
			if(null == noCarRisk.getnField6()){
				page.setMessage("每次事故每人人身伤亡赔偿（元）不能为空");
				page.setResult("error");
				return page;
			}else{ 
				if(!pnum.matcher(noCarRisk.getnField6().toString()).matches()){
				page.setMessage("输入的每次事故每人人身伤亡赔偿（元）不合法");
				page.setResult("error");
				return page;
				}
				try {
					noCarRisk.setnField6(new BigDecimal(df.format(noCarRisk.getnField6())));
				} catch (Exception e) {
					page.setMessage("输入的每次事故每人人身伤亡赔偿（元）不合法");
					page.setResult("error");
					logger.info("输入的每次事故每人人身伤亡赔偿（元）不合法", e);
					return page;
				}
		    }
			//每次事故财产损失赔偿限额
			if(null == noCarRisk.getnField20()){
				page.setMessage("每次事故财产损失赔偿限额（元）不能为空");
				page.setResult("error");
				return page;
			}else{ 
				if(!pnum.matcher(noCarRisk.getnField20().toString()).matches()){
				page.setMessage("输入的每次事故财产损失赔偿限额（元）不合法");
				page.setResult("error");
				return page;
				}
				try {
					noCarRisk.setnField20(new BigDecimal(df.format(noCarRisk.getnField20())));
				} catch (Exception e) {
					page.setMessage("输入的每次事故财产损失赔偿限额（元）不合法");
					page.setResult("error");
					logger.info("输入的每次事故财产损失赔偿限额（元）不合法", e);
					return page;
				}
		    }
			
		}else if("04A7".equals(prodType)){
			Pattern pnum = Pattern.compile("^(([1-9]\\d{0,9})|0)(\\.\\d{1,2})?$");
			DecimalFormat df = new DecimalFormat("#.00");
			//每次事故每人人身伤亡责任限额
			if(null == noCarRisk.getnField6()){
				page.setMessage("每次事故每人人身伤亡责任限额（元）不能为空");
				page.setResult("error");
				return page;
			}else{ 
				if(!pnum.matcher(noCarRisk.getnField6().toString()).matches()){
				page.setMessage("每次事故每人人身伤亡责任限额（元）不合法");
				page.setResult("error");
				return page;
				}
				try {
					noCarRisk.setnField6(new BigDecimal(df.format(noCarRisk.getnField6())));
				} catch (Exception e) {
					page.setMessage("每次事故每人人身伤亡责任限额（元）不合法");
					page.setResult("error");
					logger.info("每次事故每人人身伤亡责任限额（元）不合法", e);
					return page;
				}
		    }
			//每辆每次事故赔偿限额
			if(null == noCarRisk.getnField7()){
				page.setMessage("每辆每次事故赔偿限额（元）不能为空");
				page.setResult("error");
				return page;
			}else{ 
				if(!pnum.matcher(noCarRisk.getnField7().toString()).matches()){
				page.setMessage("每辆每次事故赔偿限额（元）不合法");
				page.setResult("error");
				return page;
				}
				try {
					noCarRisk.setnField7(new BigDecimal(df.format(noCarRisk.getnField7())));
				} catch (Exception e) {
					page.setMessage("每辆每次事故赔偿限额（元）不合法");
					page.setResult("error");
					logger.info("每辆每次事故赔偿限额（元）不合法", e);
					return page;
				}
		    }
			
		}else if("040D".equals(prodType)){
			//层及编码
			if(null == noCarRisk.getcField3()){
				page.setMessage("请选择层级编码");
				page.setResult("error");
				return page;
			}
		}else if("083A".equals(prodType)){
			Pattern pnum = Pattern.compile("^(([1-9]\\d{0,9})|0)(\\.\\d{1,2})?$");
			DecimalFormat df = new DecimalFormat("#.00");
			//每次事故赔偿限额
			if(null == noCarRisk.getnField6()){
				page.setMessage("每次事故赔偿限额（元）不能为空");
				page.setResult("error");
				return page;
			}else{ 
				if(!pnum.matcher(noCarRisk.getnField6().toString()).matches()){
				page.setMessage("每次事故赔偿限额（元）不合法");
				page.setResult("error");
				return page;
				}
				try {
					noCarRisk.setnField6(new BigDecimal(df.format(noCarRisk.getnField6())));
				} catch (Exception e) {
					page.setMessage("每次事故赔偿限额（元）不合法");
					page.setResult("error");
					logger.info("每次事故赔偿限额（元）不合法", e);
					return page;
				}
		    }
			
			
		}
		
		BigDecimal nField16 = noCarRisk.getnField16();
		if (null != nField16) {
			nField16 = nField16.divide(percentHun);
			nField16 = nField16.setScale(6, BigDecimal.ROUND_HALF_UP);
			noCarRisk.setnField16(nField16);
		}
		BigDecimal nField17 = noCarRisk.getnField17();
		if (null != nField17) {
			nField17 = nField17.divide(percentTh);
			nField17 = nField17.setScale(7, BigDecimal.ROUND_HALF_UP);
			noCarRisk.setnField17(nField17);
		}
		BigDecimal nField18 = noCarRisk.getnField18();
		if (null != nField18) {
			nField18 = nField18.divide(percentTh);
			nField18 = nField18.setScale(20, BigDecimal.ROUND_HALF_UP);
			noCarRisk.setnField18(nField18);
		}
		BigDecimal nField10 = noCarRisk.getnField10();
		if (null != nField10) {
			nField10 = nField10.divide(percentTh);
			nField10 = nField10.setScale(6, BigDecimal.ROUND_HALF_UP);
			noCarRisk.setnField10(nField10);
		}
		BigDecimal nField11 = noCarRisk.getnField11();
		if (null != nField11) {
			nField11 = nField11.divide(percentTh);
			nField11 = nField11.setScale(8, BigDecimal.ROUND_HALF_UP);
			noCarRisk.setnField11(nField11);
		}
		noCarRisk.setStatus("1");
		noCarRisk.setInsertTime(new Date());
		page.setResult("success");
		return page;
	}
	
	/**
	 * 根据险种类型返回对应amount字段中文名字
	 * @param prodType
	 * @return
	 */
	private String getAmountName(String prodType){
		String amountName = "";
		if("048K".equals(prodType)||"048C".equals(prodType)||"049B".equals(prodType)||"042O".equals(prodType)||"04A7".equals(prodType)){
			amountName = "累计责任限额（元）";
		}else if("012A".equals(prodType)||"012B".equals(prodType)){
			amountName = "保险金额/责任限额（元）";
		}else if("081J".equals(prodType)||"081R".equals(prodType)){
			amountName = "保险金额（元）/累计责任限额";
		}else if("021M".equals(prodType)){
			amountName = "每份保险金额（元）";
		}else if("080D".equals(prodType)||"080E".equals(prodType)||"081F".equals(prodType)){
			amountName = "保险金额（元）";
		}else if("081X".equals(prodType)||"081K".equals(prodType)||"080G".equals(prodType)||"083A".equals(prodType)){
			amountName = "保险金额/赔偿限额（元）";
		}else if("04A5".equals(prodType) || "040D".equals(prodType)){
			amountName = "赔偿限额（元）";
		}
		return amountName;
	}

	/**
	 * 删除险别
	 */
	@RequestMapping(value = "/riskDelete")
	public @ResponseBody Page<NocarRisk> deleteRisk(String prodCode, String riskCode, Long nField1) throws Exception {
		Page<NocarRisk> page = new Page<NocarRisk>();
		if (StrUtil.isEmpty(prodCode)) {
			page.setMessage("产品代码不能为空");
			page.setResult("error");
			return page;
		}
		if (StrUtil.isEmpty(riskCode)) {
			page.setMessage("险种代码不能为空");
			page.setResult("error");
			return page;
		}
		noCarProductService.deleteRisk(prodCode, riskCode, nField1);
		// 当产品下的所有险别都删除时 更新该产品的状态为无效
		if (0 == noCarProductService.queryProdRiskCountByCode(prodCode)) {
			NocarProd noCarProd = new NocarProd();
			noCarProd.setProdCode(prodCode);
			noCarProd.setStatus("0");
			noCarProductService.updateNocarProd(noCarProd);
		}
		page.setMessage("删除成功");
		return page;
	}

	/**
	 * 加载已添加的险别
	 */
	@RequestMapping(value = "/loadPlan")
	public @ResponseBody Page<NocarRisk> loadPlan(Integer size, Integer current, String prodCode) throws SQLException {
		// 验证产品代码是否可用TradProdInst
		Page<NocarRisk> page = new Page<NocarRisk>();
		page.setCurrent(current);
		page.setSize(size);
		Page<NocarRisk> rpage = noCarProductService.queryRiskPlanBasePage(page, prodCode);
		return rpage;
	}

	/**
	 * 查询产品类型列表
	 */
	@RequestMapping(value = "/queryProdType")
	public @ResponseBody List<DictDto> getProdTypes(String parentCode) {
		List<DictDto> prodTypeList = DictCache.getProdType(parentCode);
		return prodTypeList;
	}

	// 再给产品添加险种前校验 同一产品只能添加同一险种的约束
	private boolean isExistRisk(String prodCode, String riskCode) throws SQLException {
		return noCarProductService.isExistRisk(prodCode, riskCode);
	}

	// 产品是否存在方案关联
	private boolean isExistProdPlan(String prodCode) throws SQLException {
		return noCarProductService.isExistProdPlan(prodCode);
	}

	/**
	 * added by zzGuo@2015-9-9 14:51:51 for 财险支持共保配置（宁波智航网需求开发）begin
	 * @throws SQLException 
	 */
	@RequestMapping(value = "/conInsure")
	public String conInsureInfo(ModelMap model, HttpServletRequest request, String prodType, String prodCode) throws SQLException {
		logger.info("产品类型" + prodType + "产品编码" + prodCode);
		NocarProd prod = null;
		try {
			prod = noCarProductService.queryNocarTradProdInstById(prodCode);
			if (null == prod) {
				throw new AppException("产品代码不存在");
			} else if (null != prod && !("Y".equals(prod.getIsPool()))) {
				throw new AppException("本产品不支持共保");
			}
			List<DictDto> insureCompanyTypeList = DictCache.getDict(Constants.DICT_INSURE_COMPANY_TYPE);
			model.put("insureCompanyTypeList", insureCompanyTypeList);
			model.put("prodCode", prodCode);
			model.put("prodType", prod.getProdType());
			model.put("prodName", prod.getProdName());
			String conInsuCodeDscp = "";
			if (StrUtil.isNotEmpty(prod.getConInsuCode()) && prod.getConInsuCode().equals("01")) {
				conInsuCodeDscp = "共出";
			} else {
				conInsuCodeDscp = "共入";
			}
			model.put("conInsuCode", conInsuCodeDscp);
		} catch (AppException e) {
			model.addAttribute("dataException", e.getMessage());
			logger.info(e);
		}
		return "noCarProduct/conInsure/add";
	}

	/**
	 * added by  JJB
	 * @param model
	 * @param request
	 * @param prodCode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/downLoadProds")
	public void downLoadProds(HttpSession session,HttpServletRequest request, String prodCode,HttpServletResponse response) throws Exception {
		ServletOutputStream  outPutStream=null;
		final String userAgent = request.getHeader("USER-AGENT");
		String filename="财险产品导出.txt";
		//浏览器兼容性
		if(userAgent.indexOf("MSIE")!=-1){
			filename=java.net.URLEncoder.encode(filename, "UTF-8");//IE浏览器
		}else if(userAgent.indexOf("Mozilla")!=-1){
			filename=new String(filename.getBytes(),"ISO8859-1");//火狐浏览器
		}else{
			filename=java.net.URLEncoder.encode(filename, "UTF-8");
		}
		String[]  prods=chooseProds(prodCode);
		/*查询产品数据*/
		Map<String,Object> map=new HashMap<String,Object>();
		 map=queryProds(prods);
		 try{
				outPutStream=response.getOutputStream();
				response.setContentType("text/plain");
				response.setHeader("content-type", "text/html;charset=UTF-8");
				response.addHeader(
		                    "Content-Disposition",
		                    "attachment; filename="+filename);
				String  ss=FreeMarkerUtil.process("noCarProd.ftl", map);
				outPutStream.write(ss.getBytes());
				outPutStream.flush();
		 }catch(Exception e){
			 throw  e;
		 }finally{
			 if(outPutStream!=null){
					outPutStream.close();
				}
		 }
	}
	/*产品编码处理*/
	private String[] chooseProds(String prodCode) {
		if(StrUtil.isEmpty(prodCode)){
			return null;
		}
			String[] strs=prodCode.split(",");
			return strs;
	}

	/**
	 * 查询产品所有数据表
	 * @param prodCode
	 * @return
	 * @throws Exception
	 */
	private Map<String, Object> queryProds(String[] prodCodes) throws Exception {
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("prodCodes", prodCodes);
		 List<String> prodSqls=new ArrayList<String>();
		 List<String> riskSqls=new ArrayList<String>();
		 List<String> callSqls=new ArrayList<String>(); 
		 List<String> defulSqls=new ArrayList<String>(); 
		 List<String> propsSqls=new ArrayList<String>(); 
		/**产品导出**/
		 List<Map<String, Object>>  nocarProdsList=noCarProductService.searchNoCarProdsByprodCode(map);//产品
		 for (Map<String, Object> map2 : nocarProdsList) {
			 String sql=getInsertSql(map2, "T_NOCAR_PROD");
			 prodSqls.add(sql);
		 }
		 
		/**险种导出**/
		 List<Map<String, Object>> nocarRisksList=noCarProductService.searchNoCarRisksByprodCode(map);//产品与险种
		 for (Map<String, Object> map2 : nocarRisksList) {
			 String sql=getInsertSql(map2, "T_NOCAR_RISK");
			 riskSqls.add(sql);
		 }
		/**算法*/
		 List<Map<String, Object>> nocarRiskCalsList=noCarProductService.searchNoCarRiskCalsByprodCode(map);//算法
		 for (Map<String, Object> map2 : nocarRiskCalsList) {
			 String sql=getInsertSql(map2, "T_NOCAR_RISK_CAL");
			 callSqls.add(sql);
		 }
		/**默认值**/
		 List<Map<String, Object>>  nocarProdDefaultsList=noCarProductService.searchNoCarProdDefaultsByprodCode(map);//默认值
		 for (Map<String, Object> map2 : nocarProdDefaultsList) {
			 String sql=getInsertSql(map2, "T_NOCAR_PROD_DEFALUT");
			 defulSqls.add(sql);
		 }
		 
		 /**查询保单配置*/
		 List<Map<String, Object>>  props= nProductService.impNocarProp(map);
		 for (Map<String, Object> map2 : props) {
			 String sql=getInsertSql(map2, "T_TRAD_PROD_PROP");
			 propsSqls.add(sql);
		 }
		map.put("nocarProdsList", prodSqls);
		map.put("nocarRisksList", riskSqls);
		map.put("nocarRiskCalsList", callSqls);
		map.put("nocarProdDefaultsList", defulSqls);
		map.put("props", propsSqls);
		return map;
	}
	/**循环map返回insert语句**/
	private String getInsertSql(Map<String, Object> map,String table){
		String sql="INSERT INTO " +table;
		String cloum=" (";
		String value=" (";
		if(map!=null){
			for (String key : map.keySet()) {
				if(key.equalsIgnoreCase("prod_code")||key.equalsIgnoreCase("trad_prod_code")){
					continue;
				}
				if(key.equalsIgnoreCase("prodCode")){
					cloum+="PROD_CODE,";
					value+="'"+map.get(key)+"',";
					continue;
				}
				if(key.equalsIgnoreCase("TRADPRODCODE")){
					cloum+="TRAD_PROD_CODE,";
					value+="'"+map.get(key)+"',";
					continue;
				}
				if(key.equalsIgnoreCase("id")){
					cloum+=key+",";
					value+="(SELECT MAX(ID)+1  from "+table+") ,";
					continue;
				}
				if(key.equalsIgnoreCase("start_date")||key.equalsIgnoreCase("oper_time")||key.equalsIgnoreCase("update_time")||key.equalsIgnoreCase("OPRATE_TIME")||key.equalsIgnoreCase("CREATE_DATE")||key.equalsIgnoreCase("INSERT_TIME")){
					cloum+=key+",";
					value+="SYSDATE,";
					continue;
				}
				cloum+=key+",";
				if(map.get(key)!=null){
					value+="'"+map.get(key)+"',";
				}else{
					value+=map.get(key)+",";
				}
				
			}
			cloum=cloum.substring(0,cloum.length()-1)+" )";
			value=value.substring(0,value.length()-1)+" )";
		}
		return sql+cloum+" VALUES "+value;
	}
	/**
	 * 加载产品已经添加的共保信息
	 */
	@RequestMapping(value = "/loadProdConInsureInfo")
	public @ResponseBody Page<NocarConInsu> loadProdConInsureInfo(String prodCode) throws SQLException {
		// 验证产品代码是否可用TradProdInst
		Page<NocarConInsu> page = new Page<NocarConInsu>();
		Page<NocarConInsu> rpage = noCarProductService.queryProdConInsureInfoPage(page, prodCode);
		return rpage;
	}

	/**
	 * 保存产品共保信息
	 */
	@RequestMapping(value = "/saveProdConInsure")
	public @ResponseBody Page<NocarConInsu> saveProdConInsure(String jsonDataStr, String prodCode, HttpServletRequest request) throws Exception {
		Page<NocarConInsu> page = new Page<NocarConInsu>();
		if (StrUtil.isEmpty(jsonDataStr)) {
			page.setResult("error");
			page.setMessage("录入共保信息为空，请先添加共保信息后再次保存");
			return page;

		} else if (StrUtil.isEmpty(prodCode)) {
			page.setResult("error");
			page.setMessage("产品代码参数为空，请重试");
			return page;
		}
		List<NocarConInsu> ls = new ArrayList<NocarConInsu>();
		List temls = JsonUtils.parseJson(jsonDataStr, List.class);
		for (int i = 0; i < temls.size(); i++) {
			if (StrUtil.isNotEmpty(temls.get(i).toString())) {
				NocarConInsu nocar = new NocarConInsu();
				logger.info("JsonString" + temls.get(i).toString());
				nocar = JsonUtils.parseJson(temls.get(i).toString(), NocarConInsu.class);
				ls.add(nocar);
			}
		}
		// check business rules begin
		if (ls.size() < 2) {
			page.setResult("error");
			page.setMessage("录入的共保信息记录数至少为2条");
			return page;
		}
		BigDecimal temConPropPercent = BigDecimal.valueOf(0.000000);
		int temMainConFlagCount = 0;
		NocarConInsu temCheckConInsu = new NocarConInsu();
		NocarConInsu nextCheckConInsu = new NocarConInsu();
		for (int i = 0; i < ls.size(); i++) {
			temCheckConInsu = ls.get(i);// 获取当前对象
			// 1.check 主共保标识
			if ("1".equals(temCheckConInsu.getMAINCONFLAG())) {
				temMainConFlagCount = temMainConFlagCount + 1;
			}
			for (int j = i + 1; j < ls.size(); j++) {
				nextCheckConInsu = ls.get(j);
				if (StrUtil.isNotEmpty(temCheckConInsu.getCONCONFNO()) && StrUtil.isNotEmpty(nextCheckConInsu.getCONCONFNO())) {
					if (!(temCheckConInsu.getCONCONFNO().equals(nextCheckConInsu.getCONCONFNO()))) {
						page.setResult("error");
						page.setMessage("同一产品所有的共保协议号需相同，序号:[" + temCheckConInsu.getSEQNO() + "]的协议号和序号[" + nextCheckConInsu.getSEQNO() + "]协议号不相同");
						return page;
					}
				} else {
					page.setResult("error");
					page.setMessage("同一产品所有的共保协议号需相同,序号:[" + temCheckConInsu.getSEQNO() + "]或者序号:[" + nextCheckConInsu.getSEQNO() + "]的共保协议号为空,请检查");
					return page;
				}
				if (StrUtil.isNotEmpty(temCheckConInsu.getCONDEPTCODE()) && StrUtil.isNotEmpty(nextCheckConInsu.getCONDEPTCODE())) {
					if (temCheckConInsu.getCONDEPTCODE().equals(nextCheckConInsu.getCONDEPTCODE())) {
						page.setResult("error");
						page.setMessage("同一产品中同一保险公司最多配置一条记录，序号:[" + temCheckConInsu.getSEQNO() + "]的保险公司和序号[" + nextCheckConInsu.getSEQNO() + "]的相同");
						return page;
					}
				} else {
					page.setResult("error");
					page.setMessage("同一产品中同一保险公司最多配置一条记录，序号:[" + temCheckConInsu.getSEQNO() + "]的保险公司或者序号[" + nextCheckConInsu.getSEQNO() + "]的保险公司为空，请检查");
					return page;
				}
			}
			if (null != temCheckConInsu.getCONPROP()) {
				temConPropPercent = temConPropPercent.add(temCheckConInsu.getCONPROP().divide(percentHun).setScale(6, BigDecimal.ROUND_HALF_UP));
			} else {
				page.setResult("error");
				page.setMessage("序号:[" + temCheckConInsu.getSEQNO() + "]的共保比例不能为空,请检查");
				return page;
			}
		}
		if (1 != temMainConFlagCount) {
			page.setResult("error");
			page.setMessage("同一产品有且只能有一个主共保标识为是的记录,请检查");
			return page;
		}
		if (0 != conPropPercent.compareTo(temConPropPercent)) {
			page.setResult("error");
			page.setMessage("同一产品所有记录共保比例之和必须等于100");
			return page;
		}
		// check business rules end
		GatewayUser user = (GatewayUser) request.getSession().getAttribute(Constants.SESSION_USER);
		// 1.delet
		noCarProductService.deleteProdConInsureByProdCode(prodCode);
		// 2.save
		BigDecimal realConProp = null;
		for (int i = 0; i < ls.size(); i++) {
			realConProp = ls.get(i).getCONPROP().divide(percentHun).setScale(6, BigDecimal.ROUND_HALF_UP);
			ls.get(i).setSEQNO(new Integer(i + 1).longValue());// 重新定义seqNo
			ls.get(i).setCONPROP(realConProp);
			ls.get(i).setOPERUSER(user.getUserid());
			ls.get(i).setOPERTIME(new Date());
			ls.get(i).setCONCONFFLAG("1");// 主从协议标志(CON_CONF_FLAG)页面不录入，后台写死为1
			noCarProductService.saveProdConInsure(ls.get(i));
		}
		page.setMessage("保存成功");
		return page;
	}

	/**
	 * 查询保险期间
	 * @return
	 */
	@RequestMapping(value = "/queryInsurePeriod")
	public @ResponseBody List<DictDto> queryInsurePeriod() {
		List<DictDto> insurePeriodList = DictCache.getDict(Constants.DICT_INSURE_PERIOD);
		return insurePeriodList;
	}
}
